import { IBreadcrumbItem, Stack, DefaultButton, IButtonStyles, IStackStyles } from "@fluentui/react";
import { useBoolean } from "@fluentui/react-hooks";
import { message, Skeleton } from "antd";
import React, { useEffect, useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import Alymodel from "../../mysql_interface/model";
import { asyncgetCourseFile, asyncgetLessionByCourseid, asyncselectCoursefile, asyncvideoQuestion } from "../api/api";
import AlyplayerComponent from "../components/aliplayer";
import CourseForumView from "../components/courseforum";
import Sectionw from "../components/scetionw";
import VideoLeft from "../components/videoleft";
import { InS } from "../interface";

const buttonstyles: IButtonStyles = {
  root: { background: 'rgba(0,0,0,0)', marginRight: 24, borderColor: '#FF8461' },
  rootHovered: {
    background: '#FF8461',
    borderColor: '#FF8461'
  }
}

const rightmain: IStackStyles = {
  root:
  {
    backgroundColor: '#434343',
    height: 'calc(100vh - var(--el-header-height))',
    overflowY: 'auto',
    overflowX: 'hidden',
    width: 'calc(100vw - 336px)',
  }
}

type P = InS
const CouresView: React.FunctionComponent<P> = (prop) => {
  const [isOpen, { setTrue: openPanel, setFalse: dismissPanel }] = useBoolean(true);
  const location = useLocation()
  const params = useParams()
  const [messageApi, contextHolder] = message.useMessage();
  const [course, setcoure] = useState(getcoures)
  const [catebagid, setcatebagid] = useState(getquery)
  const [iswatch, setiswatch] = useState(getiswatch)
  const [lession, setlession] = useState(getlession)
  const [catebag, setcatebag] = useState(getcatebag)
  const [courselist, setcourselist] = useState<Alymodel.IMcourse[]>(getcourselist)
  const [items, setitems] = useState(getitems)
  const [question, setquestion] = useState<Alymodel.Ivideoquestion[]>([])
  const [files, setfiles] = useState<Alymodel.Ifileurl[]>([])
  const [teacherfiles, setteacherfiles] = useState<Alymodel.Iteachercoursefile[]>([])
  const [show, setshow] = useState<false | 'vector' | 'video' | 'question'>(false)

  function getcatebag() {
    return prop.getCatebag.find(v => v.ID === Number(catebagid))
  }
  function getitems(): IBreadcrumbItem[] {
    return [
      { text: '我的课程', key: '/secure/myclass', href: '#/secure/myclass' },
      { text: catebag?.name ? catebag.name : '课程组', key: '/catebag/' + catebag?.ID, href: '#/catebag/' + catebag?.ID },
      { text: course?.name ? course.name : '课程组', key: '/course/' + catebag?.ID, isCurrentItem: true },
    ];
  }
  function getcourselist() {
    const n = prop.getCoursecatebag.filter(e => e.catebagid === Number(catebagid)).map(v => v.cid)
    const b = prop.getCourse.filter(e => n.includes(e.ID))
    return b
  }
  function getquery() {
    const params = new URLSearchParams(location.search.substring(1))
    return Number(params.get('catebag'))
  }
  function getcoures() {
    return prop.getCourse.find(v => v.ID === Number(params?.ID))
  }
  function getiswatch() {
    return prop.getuserUserCourse.some((v) => v.course_ID == Number(params?.ID));
  }
  function getlession(): Alymodel.IMlession {
    const search = new URLSearchParams(location.search.substring(1))
    const lession = Number(search.get('lession')) || 0

    if (iswatch) {
      const data = prop.getCourse.find((v) => v.ID == Number(params?.ID));
      if (data?.lession) return data.lession[lession]
    }
    return {};
  }

  async function start(): Promise<false | Alymodel.IMlession['type']> {
    try {
      if (iswatch) {
        const lessions = await asyncgetLessionByCourseid({ cid: Number(params?.ID) });
        if (!lessions) {
          messageApi.warning("课程马上开放请先观看其他课程");
          return false
        }
        const search = new URLSearchParams(location.search.substring(1))
        const key = Number(search.get('lession')) || 0
        const lession = lessions[key]
        if (!lession) {
          messageApi.warning("课程马上开放请先观看其他课程");
          return false
        }
        const files = await asyncgetCourseFile({ cid: Number(params?.ID) });
        setfiles(files)
        const teacherfile = await asyncselectCoursefile({ cid: Number(params?.ID) });
        setteacherfiles(teacherfile)
        const { type } = lession;
        if (type === "video") {
          const question = await asyncvideoQuestion({ lid: lession.ID });
          setquestion(question)
        }
        return type
      }
    } catch (err) {
      messageApi.warning("课程马上开放请先观看其他课程");
    }
    return false
  }

  useEffect(() => {
    const root = document.querySelector<HTMLDivElement>('#root')
    if (root) {
      root.style.backgroundColor = "rgb(67, 67, 67)"
    }
    return () => {
      const root = document.querySelector<HTMLDivElement>('#root')
      if (root) {
        root.style.backgroundColor = ""
      }
    }
  }, [])

  useEffect(() => {
    setitems(getitems)
  }, [catebag, course])


  useEffect(() => {
    setcatebagid(getquery)
    setcoure(getcoures)
    setiswatch(getiswatch)
    setlession(getlession)
    setcatebag(getcatebag)
    setcourselist(getcourselist)
    start().then(e => {
      if (e)
        setshow(e)
    })
  }, [prop])


  useEffect(() => {
    setcatebagid(getquery)
    setcoure(getcoures)
    setiswatch(getiswatch)
    setlession(getlession)
    setcatebag(getcatebag)
    setcourselist(getcourselist)
    start().then(e => {
      if (e)
        setshow(e)
    })
  }, [params.ID])

  return (
    <Stack horizontal disableShrink styles={{ root: { position: 'relative' } }}>
      {contextHolder}
      <Stack.Item style={{ width: 336 }}>
        <VideoLeft course={course} files={files} teacherfiles={teacherfiles} catebag={catebag} courselist={courselist} userCoures={prop.getuserCourse} />
      </Stack.Item>
      <Stack.Item disableShrink grow styles={rightmain}>
        <Stack>
          <div className="container-fluid" >
            {
              (prop.getuser && course && course.ID && lession?.ID) ? (
                <div className="row">

                  {
                    show === 'video' ?
                      <AlyplayerComponent lid={lession.ID} question={question} course={course} getuser={prop.getuser} />
                      : <></>
                  }
                  {
                    show === 'vector' ?
                      <Sectionw cid={course.ID} getuser={prop.getuser} num={1} />
                      : <></>
                  }
                  {
                    !show ? <Skeleton paragraph={{ rows: 10 }}><br /></Skeleton> : <></>
                  }
                </div>
              ) : <></>
            }

          </div>
        </Stack>
        <Stack styles={{ root: { height: 48, paddingTop: 12, paddingRight: 12 } }} >
          <div className="text-right">
            {
              files.map((e, key) => {
                return (
                  <DefaultButton key={'bb_' + key} styles={buttonstyles}>
                    <a href={e.file_URL} style={{ color: '#fff' }} target="_blank">{e.name}</a>
                  </DefaultButton>
                )
              })
            }
            {
              teacherfiles.map((e, key) => {
                return (
                  <DefaultButton key={'a_' + key} styles={{ root: { backgroundColor: 'rgba(0,0,0,0)', color: '#fff', borderColor: '#ffffff', marginLeft: 24 }, rootHovered: { backgroundColor: 'rgba(0,0,0,0)', borderColor: '#ff8661', color: '#fff' }, rootDisabled: { backgroundColor: 'rgba(0,0,0,0)', color: '#fff', borderColor: '#8C8C8C' } }}>
                    <a href={e.fileurl} target="_blank">教师资料</a>
                  </DefaultButton>
                )
              })
            }
          </div>
        </Stack>
        <Stack styles={{ root: { height: 48, paddingTop: 12, paddingRight: 12 } }}>
          {
            (params?.ID && prop.getuser) ? <CourseForumView {...prop} courseid={Number(params.ID)} catebag={catebag?.name || ''} coursename={course?.name || ''} user={prop.getuser} ></CourseForumView> : '555'
          }
        </Stack>
      </Stack.Item>
    </Stack>
  )
}

export default CouresView